package com.ruoyi.web.runner;

import com.ruoyi.activity.service.IActivityService;
import com.ruoyi.activity.service.IContestService;
import com.ruoyi.blog.service.BlogService;
import com.ruoyi.common.config.MyThreadPoolConfig;
import com.ruoyi.common.constant.ActivitysConstant;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.model.activity.Activity;
import com.ruoyi.model.blog.Blog;
import com.ruoyi.model.contest.Contest;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author : 张怀秋
 **/
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ViewCountSaveRedisHashController implements CommandLineRunner {
    private final MyThreadPoolConfig myThreadPoolConfig;
    private final IContestService contestService;
    private final IActivityService activityService;
    private final BlogService blogService;
    private final RedisCache redisCache;


    @Override
    public void run(String... args) throws Exception {
        //使用多线程的方式 将所有的 文章 竞赛 活动 等等的浏览量 在项目启动的使用保存进redis
        ThreadPoolExecutor executor = myThreadPoolConfig.threadPoolExecutor();
        //1.保存竞赛浏览量
        CompletableFuture.runAsync(() -> {
            System.err.println("开始保存竞赛浏览量进入redis");
            Map<String, Integer> map = contestService.list().stream().collect(Collectors.toMap(Contest::getId, Contest::getViewNum));
            redisCache.setCacheMap(ActivitysConstant.CONTEST_KEY, map);
        }, executor);
        //2.保存活动浏览量
        CompletableFuture.runAsync(() -> {
            System.err.println("开始保存活动浏览量进入redis");
            Map<String, Integer> map = activityService.list().stream().collect(Collectors.toMap(Activity::getId, Activity::getViewNum));
            redisCache.setCacheMap(ActivitysConstant.ACTIVITY_KEY, map);
        }, executor);
        //3.保存文章浏览量
        CompletableFuture.runAsync(() -> {
            System.err.println("开始保存文章浏览量进入redis");
            Map<String, Integer> map = blogService.list().stream().collect(Collectors.toMap(Blog::getId, Blog::getViewCount));
            redisCache.setCacheMap(ActivitysConstant.BLOG_KEY, map);
        }, executor);
    }
}
